package com.polaris.live.ui.me.beans

import android.animation.LayoutTransition
import android.animation.ObjectAnimator
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.adapter.MyBeansBannerAdapter
import com.polaris.live.adapter.MyBeansSeatAdapter
import com.polaris.live.adapter.beans.MyBeansAdapter
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.ActivityMyBeansBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog.MyBeansInstructionDialog
import com.polaris.live.dialog.MyBeansWhatDialog
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.popup.MyBeansStartPlayPopup
import com.polaris.live.resp.back_resp.CoinBeansResp
import com.polaris.live.resp.back_resp.LiveShowMessageResp
import com.polaris.live.resp.back_resp.MyBeansSeatTabBean
import com.polaris.live.resp.bean.MyBeansBannerBean
import com.polaris.live.resp.bean.MyBeansBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.viewmodel.MyBeansViewModel
import com.polaris.live.widget.AnimUtils
import com.zhpan.bannerview.constants.PageStyle
import java.util.Collections

/**
 * MyBeans页面
 *
 * @author Created by 半仙 on 2023/10/24/024 15:14
 */
class MyBeansActivity : BaseVbActivity<MyBeansViewModel, ActivityMyBeansBinding>() {

    private var mAdapter: MyBeansAdapter? = null
    private var mCoinBeansResp: CoinBeansResp? = null
    private var mLiveShowResp: LiveShowMessageResp? = null

    private val mBannerAdapter by lazy { MyBeansBannerAdapter() }

    override fun ImmersionBarBuilder.buildImmersionBar() {
        setTitleBar(mBinding.bvTitle)
        setStatusBarDarkFont(false)
    }

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.livesShowMessage()
        initObsever()
        initListener()
    }

    override fun onResume() {
        super.onResume()
        mViewModel.getMyBeans()
    }

    private fun initListener() {
        mBinding.bvTitle.setOnRightClientListener {
            AppConfigManager.getConfig(CommonConst.Configs.ossUrl)?.let {
                val map = mutableMapOf<String, String>()
                if (mCoinBeansResp?.agencyGainCoin != null && mCoinBeansResp?.agencySendGainCoin != null) {
                    map["type"] = "family"
                }
                RouterUtils.routerWeb("${it}/static/app/index.html#/coinBeansDetail", map)
            }
        }
        mBinding.llChat.setOnSingleClickListener {
            Router.builder(RoutePath.MY_CHAT_PRICE_ACTIVITY)
                .navigation(this)
        }
        mBannerAdapter.setOnWithdrawClick {
            mCoinBeansResp?.let {
                if (!it.withdrawalWithinAllowedTime) {
                    Router.builder(RoutePath.MYWITHDRAW_ACTIVITY).navigation(this)
                } else {
                    GlobalDialogManager.showWithdrawTipDialog(this)
                }
            }
        }
        mBannerAdapter.setOnMyBeansWhatClick {
            XPopup.Builder(this)
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .asCustom(MyBeansInstructionDialog(this))
                .show()
        }
        mBannerAdapter.setOnGetMoreBeansClick {
            mLiveShowResp?.let {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .asCustom(MyBeansStartPlayPopup(this, it) {
                        if (it == LiveConst.Type.PARTY_LIVE) {
                            mViewModel.getPartyRoom()
                        } else {
                            StartLiveProxy.startReadyLive(this, this, mViewModel, it)
                        }
                    })
                    .show()
            }
        }
        mBinding.myBeansBanner.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mBinding.apply {
                    setTitleR(position)
                    if (position == 0) {
                        inAnimation(mBinding.ivMyBeansBack)
                        outAnimation(mBinding.ivMyBeansBackPurple)
                        setTextColor(ColorUtils.getColor(R.color.color_924a1c))
                        setTagTextColor(ColorUtils.getColor(R.color.color_924a1c_30))
                        if (mCoinBeansResp?.info?.siteDuration != null) {
                            mBinding.bannerSeat.visibility = View.VISIBLE
                            mBinding.llSeatTab.visibility = View.VISIBLE
                        }
                    } else {
                        mBinding.bannerSeat.visibility = View.GONE
                        mBinding.llSeatTab.visibility = View.GONE
                        inAnimation(mBinding.ivMyBeansBackPurple)
                        outAnimation(mBinding.ivMyBeansBack)
                        setTextColor(ColorUtils.getColor(R.color.color_9757ff))
                        setTagTextColor(ColorUtils.getColor(R.color.color_9757ff_30))
                    }
                    mAdapter?.setAdapterColor(position)
                }
            }
        })
        mBinding.tvMine.setOnSingleClickListener {
            mBinding.myBeansBanner.setCurrentItem(0, true)
        }
        mBinding.tvFamily.setOnSingleClickListener {
            mBinding.myBeansBanner.setCurrentItem(1, true)
        }
        mBinding.tvSeatDataTab.setOnSingleClickListener {
            mBinding.tvSeatDataTab.setBackgroundResource(R.drawable.my_beans_select_seat_data_back)
            mBinding.tvLastZseatDataTab.setBackgroundResource(R.drawable.my_beans_no_select_seat_data_back)
            mBinding.bannerSeat.setCurrentItem(0, true)
        }
        mBinding.tvLastZseatDataTab.setOnSingleClickListener {
            mBinding.tvLastZseatDataTab.setBackgroundResource(R.drawable.my_beans_select_seat_data_back)
            mBinding.tvSeatDataTab.setBackgroundResource(R.drawable.my_beans_no_select_seat_data_back)
            mBinding.bannerSeat.setCurrentItem(1, true)
        }
    }

    private fun initObsever() {
        mViewModel.mPartyRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.roomId?.isNotEmpty() == true) {
                    val liveType = UserManager.getUser().live?.liveType
                    StartLiveProxy.builder(this)
                        .recoverLive(mViewModel, liveType, it.roomId)
                } else {
                    Router.builder(RoutePath.SET_PARTY_COVER_ACTIVITY)
                        .navigation(this)
                }
            })
        }
        mViewModel.mCoinBeansLiveData.observe(this) { resultState ->
            parseState(resultState, {
                initUi(it)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        mViewModel.mLiveShowLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mLiveShowResp = it
            })
        }
    }

    private fun initUi(coinBeansResp: CoinBeansResp) {
        this.mCoinBeansResp = coinBeansResp
        mBinding.apply {
            val bannerList = mutableListOf<MyBeansBannerBean>()
            bannerList.add(
                MyBeansBannerBean(
                    coinBeansResp.userGainCoin,
                    coinBeansResp.userSendGainCoin,
                    coinBeansResp.allowWithdraw
                )
            )
            if (coinBeansResp.agencyGainCoin != null && coinBeansResp.agencySendGainCoin != null) {
                bannerList.add(
                    MyBeansBannerBean(
                        coinBeansResp.agencyGainCoin,
                        coinBeansResp.agencySendGainCoin,
                        coinBeansResp.allowWithdraw
                    )
                )
                mBinding.llTitleTab.visibility = View.VISIBLE
            }

            myBeansBanner.apply {
                registerLifecycleObserver(lifecycle)
                setAdapter(mBannerAdapter)
                setCanLoop(false)
                setPageMargin(8.dp)
                setRevealWidth(8.dp, 8.dp)
                setIndicatorVisibility(View.GONE)
                setPageStyle(PageStyle.MULTI_PAGE_SCALE, 0.95f)
                create(bannerList)
            }

            // TODO 只有sala需要，其他的包不需要这里
//            if (UserManager.getUser().extension?.allowWithdraw == true) {
                llContent.visibility = View.VISIBLE
//            } else {
//                llContent.visibility = View.GONE
//            }

            if (coinBeansResp.info != null) {
                llBottom.visibility = View.VISIBLE
                //Today Rewards
//                val isShowToday =
//                    coinBeansResp.info.chatBeans == null || coinBeansResp.info.liveBeans == null || coinBeansResp.info.gameBeans == null
                val isShowToday = coinBeansResp.info.liveBeans == null || coinBeansResp.info.gameBeans == null

                if (!isShowToday) {
                    tvChat.text = "${coinBeansResp.info.chatBeans}"
                    tvLive.text = "${coinBeansResp.info.giftBeans}"
                    tvLiveRewards.text = "${coinBeansResp.info.gameBeans}"
                } else {
                    llToday.visibility = View.GONE
                }

                //上周数据
                val siteDuration = coinBeansResp.info.siteDuration
                if (siteDuration != null) {
                    mBinding.llSeatTab.visibility = View.VISIBLE
                    mBinding.bannerSeat.visibility = View.VISIBLE
                    val seatList = mutableListOf<MyBeansSeatTabBean>()
                    seatList.add(
                        MyBeansSeatTabBean(
                            StringUtils.getString(string.today_seat_time, siteDuration.todayMinute),
                            StringUtils.getString(string.week_seat_time, siteDuration.weekHour),
                            StringUtils.getString(string.week_day_seat_time, siteDuration.validDays)
                        )
                    )
                    seatList.add(
                        MyBeansSeatTabBean(
                            StringUtils.getString(string.last_week_seat_time, siteDuration.lastWeekHour),
                            StringUtils.getString(string.last_week_seat_day, siteDuration.lastValidDay),
                        )
                    )
                    bannerSeat.apply {
                        registerLifecycleObserver(lifecycle)
                        setAdapter(MyBeansSeatAdapter())
                        setCanLoop(false)
                        setUserInputEnabled(false)
                        setIndicatorVisibility(View.GONE)
                        create(seatList)
                    }
                    mBinding.llCenter.layoutTransition = LayoutTransition()
                } else {
                    mBinding.llSeatTab.visibility = View.GONE
                    mBinding.bannerSeat.visibility = View.GONE
                }


                if (coinBeansResp.minGainCoin != null) {
                    val userIsShow = CommonCache.getUserIsShow()
                    if (userIsShow == AppConst.NO) {
                        XPopup.Builder(this@MyBeansActivity)
                            .hasShadowBg(true)
                            .isDestroyOnDismiss(true)
                            .asCustom(MyBeansWhatDialog(this@MyBeansActivity, coinBeansResp))
                            .show()
                    }
                }

                //Week Rewards
                if (coinBeansResp.info.weekBeans != null) {
                    llWeek.visibility = View.VISIBLE
                    val weekBeans = coinBeansResp.info.weekBeans
                    val keys = weekBeans.keys

                    if (!CollectionUtils.isEmpty(keys)) {

                        val numList = weekBeans.values

                        val maxNumber = Collections.max(numList)

                        val beansList = mutableListOf<MyBeansBean>()
                        weekBeans.forEach { (t, u) ->
                            beansList.add(MyBeansBean(t, u))
                        }
                        mAdapter = MyBeansAdapter(maxNumber)
                        recycler.apply {
                            adapter = mAdapter
                            itemAnimator = null
                            layoutManager = LinearLayoutManager(this@MyBeansActivity)
                        }
                        beansList.reverse()
                        mAdapter?.setList(beansList)
                    } else {
                        llWeek.visibility = View.GONE
                    }
                } else {
                    llWeek.visibility = View.GONE
                }

                //chat price
//                if (coinBeansResp.info.chatPrice == null) {
//                    llChat.visibility = View.GONE
//                } else {
//                    minutePrice.text = "${coinBeansResp.info.chatPrice}"
//                    llChat.visibility = View.VISIBLE
//                }
                llChat.visibility = View.GONE
            } else {
                llBottom.visibility = View.GONE
            }
        }
    }

    private fun setTextColor(@ColorInt color: Int) {
        mBinding.apply {
            tvToday.setTextColor(color)
            tvWeek.setTextColor(color)
            tvChat.setTextColor(color)
            tvLive.setTextColor(color)
            tvLiveRewards.setTextColor(color)
        }
    }

    private fun setTagTextColor(@ColorInt color: Int) {
        mBinding.apply {
            tvTagCall.setTextColor(color)
            tvTagGame.setTextColor(color)
            tvTagGift.setTextColor(color)
        }
    }

    private fun setTitleR(position: Int) {
        mBinding.apply {
            if (position == 0) {
                tvMine.setTextColor(ColorUtils.getColor(R.color.color_924a1c))
                tvMine.setBackgroundResource(R.drawable.my_beans_title_select_back)
                tvFamily.setTextColor(ColorUtils.getColor(R.color.white))
                tvFamily.setBackgroundResource(0)
            } else {
                tvMine.setTextColor(ColorUtils.getColor(R.color.white))
                tvMine.setBackgroundResource(0)
                tvFamily.setTextColor(ColorUtils.getColor(R.color.color_9757ff))
                tvFamily.setBackgroundResource(R.drawable.my_beans_title_select_back)
            }
        }
    }

    private fun inAnimation(imageView: ImageView) {
        if (imageView.alpha == 1f) return
        val fadeInDuration = 250L // 淡入动画持续时间，单位毫秒
        // 创建一个属性动画来改变图片的透明度
        val fadeInAnimation = ObjectAnimator.ofFloat(imageView, "alpha", 0f, 1f)
        fadeInAnimation.duration = fadeInDuration // 设置动画持续时间
        // 启动动画
        AnimUtils.run(imageView, fadeInAnimation)
    }

    private fun outAnimation(imageView: ImageView) {
        if (imageView.alpha == 0f) return
        val fadeInDuration = 250L // 淡入动画持续时间，单位毫秒
        // 创建一个属性动画来改变图片的透明度
        val fadeInAnimation = ObjectAnimator.ofFloat(imageView, "alpha", 1f, 0f)
        fadeInAnimation.duration = fadeInDuration // 设置动画持续时间
        // 启动动画
        AnimUtils.run(imageView, fadeInAnimation)
    }
}